<template>
  <div class="p-4">
    <el-card>
      <div class="mb-4 flex items-center gap-3">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter="fetchData"
          style="width: 200px"
        />
        <el-select
          v-model="selectedSubject"
          placeholder="请选择学科"
          clearable
          style="width: 180px"
          @change="fetchData"
        >
          <el-option
            v-for="item in subjectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="fetchData">查询</el-button>

        <el-button
          v-if="userSystemRole !== 'student'"
          type="primary"
          @click="openForm()"
          >新增试卷</el-button
        >
      </div>

      <el-table
        :data="paperList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="试卷ID" />
        <el-table-column prop="name" label="试卷名称" />
        <el-table-column prop="subject" label="所属学科" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <!-- 学生和非学生共有 -->
            <el-button size="small" type="primary" @click="goToAnswer(row)">
              开始答题
            </el-button>
            <el-button size="small" type="info" @click="viewDetail(row)">
              查看详情
            </el-button>

            <!-- 非学生才能看到 -->
            <template v-if="userSystemRole !== 'student'">
              <el-button size="small" @click="openForm(row)">编辑</el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row.name)"
                >删除</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="mt-4"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </el-card>

    <el-dialog
      :title="form.id ? '编辑试卷' : '新增试卷'"
      v-model="formVisible"
      width="600px"
      v-if="userSystemRole !== 'student'"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="试卷名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="所属学科">
          <el-select v-model="form.subject" placeholder="请选择学科">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="试题列表">
          <div class="w-full">
            <div
              v-for="(question, index) in form.questions"
              :key="index"
              class="flex items-center gap-2 mb-2"
            >
              <el-select
                v-model="form.questions[index]"
                filterable
                allow-create
                default-first-option
                placeholder="请选择或输入题目"
                style="flex: 1"
              >
                <el-option
                  v-for="item in questionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <!-- 取消选择按钮 -->
              <el-button type="warning" @click="form.questions[index] = ''">
                取消选择
              </el-button>

              <!-- 删除该题按钮 -->
              <el-button type="danger" @click="removeQuestion(index)">
                删除选择
              </el-button>
            </div>
            <el-button type="primary" plain @click="addQuestion"
              >添加题目</el-button
            >
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  getPaperList,
  createPaper,
  updatePaper,
  deletePaper,
} from "../api/paper";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSubjects } from "../api/subject";
import { getQuestions } from "../api/Practice";
import { getUserProfile } from "../api/userProfiles.js";

const userSystemRole = ref(""); // 新增：存角色
const questionOptions = ref([]);
const subjectOptions = ref([]);
const router = useRouter();
const paperList = ref([]);
const searchKeyword = ref("");
const selectedSubject = ref("");
const page = ref(1);
const pageSize = 10;
const total = ref(0);
const loading = ref(false);
const viewDetail = (row) => {
  router.push(`/api/paper/detail/${encodeURIComponent(row.name)}`);
};

const fetchAllQuestions = async () => {
  const res = await getQuestions();
  if (res.code === 200) {
    questionOptions.value = res.data.map((item) => ({
      label: item.title,
      value: item.title,
    }));
  } else {
    ElMessage.error("获取题库题目失败");
  }
};

async function fetchUserRole() {
  try {
    const res = await getUserProfile();
    if (res.code === 200 && res.data) {
      userSystemRole.value = res.data.userSystemRole || "";
    }
  } catch (e) {
    userSystemRole.value = "";
  }
}

const formVisible = ref(false);
const form = ref({
  id: null,
  name: "",
  subject: "",
  questions: [], // 题目数组，每项包含 title
});

const addQuestion = () => {
  form.value.questions.push(""); // 直接是字符串
};

const removeQuestion = (index) => {
  form.value.questions.splice(index, 1);
};

const fetchSubjects = async () => {
  const res = await getSubjects();
  if (res.code === 200) {
    subjectOptions.value = res.data.map((item) => ({
      label: item.questionsSubject,
      value: item.questionsSubject,
    }));
  } else {
    ElMessage.error("获取学科列表失败");
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getPaperList({
      page: page.value,
      pageSize,
      keyword: searchKeyword.value.trim(),
      subject: selectedSubject.value || undefined, // 避免传空字符串
    });
    if (res.code === 200) {
      paperList.value = res.data.records || res.data;
      total.value = res.data.total || res.data.length;
    } else {
      ElMessage.error("试卷获取失败");
    }
  } catch (error) {
    ElMessage.error("请求出错");
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (val) => {
  page.value = val;
  fetchData();
};

const resetSearch = () => {
  searchKeyword.value = "";
  selectedSubject.value = "";
  page.value = 1; // 重置页码
  fetchData();
};

const goToAnswer = (paper) => {
  router.push(`/api/paper/answer/${paper.name}`);
};

const openForm = (row = null) => {
  if (row) {
    form.value = {
      ...row,
      questions: Array.isArray(row.tiTle) ? [...row.tiTle] : [],
    };
  } else {
    form.value = {
      id: null,
      name: "",
      subject: "",
      questions: [],
    };
  }
  formVisible.value = true;
};

const handleSubmit = async () => {
  if (!form.value.name || !form.value.subject) {
    return ElMessage.warning("请填写完整信息");
  }

  // 过滤掉空题目标题
  const validTitles = form.value.questions.filter((q) => q && q.trim() !== "");

  if (validTitles.length === 0) {
    return ElMessage.warning("请至少填写一个题目");
  }

  const payload = {
    id: form.value.id,
    name: form.value.name,
    subject: form.value.subject,
    tiTle: validTitles, // 👈 直接是字符串数组
  };

  let res;
  if (form.value.id) {
    res = await updatePaper(payload);
  } else {
    res = await createPaper(payload);
  }

  if (res.code === 200) {
    ElMessage.success("操作成功");
    formVisible.value = false;
    fetchData();
  } else {
    ElMessage.error(res.msg || "操作失败");
  }
};

const handleDelete = async (name) => {
  ElMessageBox.confirm("确定删除该试卷吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      const res = await deletePaper(name);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        fetchData();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 页面初始化
async function initPage() {
  await fetchUserRole(); // 先获取角色
  await Promise.all([fetchSubjects(), fetchAllQuestions(), fetchData()]);
}

onMounted(initPage);
</script>
